﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Raytracererer
{
    public class Sphere : Primitive
    {
        public Vector3 center;
        protected double radius;

        public Sphere(double radius, Vector3 center, Color color)
        {
            this.center = center;
            this.radius = radius;
            this.color = color;
        }

        Color m_color;
        double m_transparency;
        double m_reflectivity;
        double m_refractiveIndex;
        double m_diffuse;
        Color m_specularity;

        public Color color
        {
            get { return m_color; }
            set { m_color = value; }
        }
        public double transparency
        {
            get { return m_transparency; }
            set { m_transparency = value; }
        }
        public double reflectivity
        {
            get;
            set;
        }
        public double refractionIndex
        {
            get { return m_refractiveIndex; }
            set { m_refractiveIndex = value; }
        }
        public double diffuse
        {
            get;
            set;
        }
        public Color specularity
        {
            get;
            set;
        }

        public double Intersect(Ray ray, out Vector3 position)
        {
            var aMinusC = ray.Position - center;
            var rootSquared = (ray.Direction * aMinusC) * (ray.Direction * aMinusC) - aMinusC * aMinusC + radius * radius;
            if (rootSquared >= 0)
            {
                double dist;
                if ((aMinusC).LengthSquared() > (radius * radius))
                    dist = -(ray.Direction * aMinusC) - Math.Sqrt(rootSquared);
                else
                    dist = -(ray.Direction * aMinusC) + Math.Sqrt(rootSquared);
                position = ray.Position + ray.Direction * dist;
                return dist;
            }
            position = null;
            return -1;
        }

        public Vector3 Normal(Vector3 position)
        {
            return (position - center).Normalized();
        }
        public virtual Color ColorAt(Vector3 position)
        {
            return m_color;
        }

        public bool isIn(Vector3 position)
        {
            if ((center - position).LengthSquared() <= radius * radius)
                return true;
            return false;
        }
    }
}
